//
//  MyOrdersViewController.m
//  WeiWeiHaircut
//
//  Created by 超群 on 15/10/15.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "MyOrdersViewController.h"
#import "MyOrderCell.h"
#import "QZMyOrderDetailVc.h"
#import "QZOrderModel.h"
#import "MJRefresh.h"
@interface MyOrdersViewController () <UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *tableSource;//数据源

@end

@implementation MyOrdersViewController
{

    UIButton *_selectButton;//选中的按钮
    NSInteger _orderStart;//订单状态
    NSInteger _pageno;//翻页号
}

-(NSMutableArray *)tableSource{
    if (_tableSource == nil) {
        _tableSource = [NSMutableArray array];
    }
    return _tableSource;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _orderStart = -1;
    [self titleWithSting:@"我的订单"];
    [self addBtnOnNavWithTitle:@"我" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 30, 20) andDirection:left];
    [self buildUI];
    [self buildTableViewUI];
    [self downoadDatas];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _pageno = 1;
        [self downoadDatas];
    }];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _pageno ++;
        
        [self downoadDatas];

    }];

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _pageno = 1;
    [self downoadDatas];
}
-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)buildUI
{
    
    NSArray* array = @[@"全部",@"待付款",@"待发货",@"待收货",@"售后"];
    CGFloat bw = WIDTH/array.count;
    for (int i = 0 ; i<array.count; i++) {
        
        UIButton* button = [[UIButton alloc]initWithFrame:CGRectMake(i*(bw+1), 0,bw , 30)];
        button.tag = i+999;
        
        [button addTarget:self action:@selector(buttonTap:) forControlEvents:UIControlEventTouchUpInside];
        [button setTitleColor:SBpurpleColor forState:UIControlStateSelected];
        [button setTitleColor:TabBarTitleColor forState:UIControlStateNormal];
        
        [button setTitle:array[i] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        if (i == 0) {
            button.selected = YES;
            _selectButton = button;
        }
        [self.topView addSubview:button];
//        [_topBtnArr addObject:button];
    }
    for (int i = 1; i<array.count; i++) {
        UIView* linView = [[UIView alloc]initWithFrame:CGRectMake(i*bw+i, 0, 1, 30)];
        linView.backgroundColor = groupDarkGrayColor;
        [self.topView addSubview:linView];
    }
}
- (void) buttonTap:(UIButton*)sender
{
    
    _pageno = 1;
    _selectButton.selected = NO;
    _selectButton = sender;
    _selectButton.selected = YES;
    switch (sender.tag-999) {
        case 0:{//全部
            _orderStart = -1;
        }break;
        case 1:{//待付款
            _orderStart = 0;
        }break;
        case 2:{//待发货
            _orderStart = 1;
        }break;
        case 3:{//待收货
            _orderStart = 2;
        }break;
        case 4:{//s售后,已完成
            _orderStart = 3;
        }break;

            
        default:
            break;
    }
    [self downoadDatas];
    
}


- (void)buildTableViewUI
{
    self.tableView.delegate         = self;
    self.tableView.dataSource       = self;
    self.tableView.separatorStyle   = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor  = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyOrderCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([MyOrderCell class])];
}

#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tableSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 118;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    QZMyOrderDetailVc* payVC = [[QZMyOrderDetailVc alloc]initWithNibName:nil bundle:nil];
    payVC.hidesBottomBarWhenPushed  = YES;
    QZOrderModel *model = self.tableSource[indexPath.row];
    
    payVC.tmpOrder = model;
  
    [self.navigationController pushViewController:payVC animated:YES];
}

#pragma mark - tableView datasource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyOrderCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MyOrderCell class]) forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    QZOrderModel *model = self.tableSource[indexPath.row];
    
    cell.textaLabel.text = [NSString stringWithFormat:@"共%ld件商品,合计￥%@",model.amount,model.price];
    //
    NSInteger x=[cell.textaLabel.text rangeOfString:@"￥"].location;
    NSInteger len = cell.textaLabel.text.length;
    
    //多颜色
    NSMutableAttributedString* attributedString    = [[NSMutableAttributedString alloc]initWithString:cell.textaLabel.text];
    
    
    [attributedString addAttribute:NSForegroundColorAttributeName
                             value:SBpurpleColor
                             range:NSMakeRange(x,len-x)];
    
    
    cell.orderTypeLabel.text = [self starString:model.orderStatus];
    
    cell.textaLabel.attributedText = attributedString;
    cell.orderNUmber.text = model.order_num;
    cell.orderTitle.text = model.order_title[0];
    
    return cell;
}
- (void)downoadDatas{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdOrderList"];
    NSDictionary *dic = @{
                          @"user_id":[QZUserInfo userId],
                          @"order_status":@(_orderStart),
                          @"page":@(_pageno),
                          @"sort":@"orderTime",
                          @"sort_type":@"right",
                          @"limit":@(6)
                          };
    if (self.tableSource.count>0) {
        self.request.isShowHUD = NO;
    }else{
        self.request.isShowHUD = YES;
    }
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"获取订单列表" stopRequest:YES isSerializer:NO isCache:YES];
    
}
-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    if ([tag isEqualToString:@"获取订单列表"]) {
        NSArray *datas = value[@"data"][@"data"][@"list"];
        
        if (_pageno == 1) {
            [self.tableSource removeAllObjects];
        }
        for (NSDictionary *dic in datas) {
            NSError *error = nil;
            QZOrderModel  *model = [[QZOrderModel alloc] initWithDictionary:dic error:&error];
            [self.tableSource addObject:model];
        }
        [self.tableView reloadData];
    }
    
    [self.tableView.header endRefreshing];
    [self.tableView.footer endRefreshing];
}
/** 订单状态 */
-(NSString *)starString:(NSInteger)index{
    
    //@"待发货",@"待收货",@"交易成功",@"退款中",@"未付款"
  //  (0待付款(1待发货(2待收货(3售后
    NSString *string = nil;
   
    switch (index) {
        case 0:
            string = @"未付款";
            break;
        case 1:
            string = @"待发货";
            break;
        case 2:
            string = @"待收货";
            break;
        case 3:
            string = @"退款中";
            break;
        case 4:
            string = @"已退款";
            break;
        case 5:
            string = @"交易完成";
            break;
        case -1:
            string = @"已取消";
            break;
            
        default:
            break;
    }
    
    return string;
}

@end
